﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JGSY.LHBS
{

    // 静态工具类（可跨项目复用）
    public static class FormHelper
    {
        private static Dictionary<Type, Form> _formCache = new Dictionary<Type, Form>();


        /// <summary>
        /// 显示指定类型的窗体，并支持初始化设置
        /// </summary>
        /// <typeparam name="T">窗体类型</typeparam>
        /// <param name="initializer">窗体初始化委托</param>
        /// <returns>已显示的窗体实例</returns>
        public static T ShowForm<T>(Form mdiParent = null, Action<T> initializer = null) where T : Form, new()
        {
            Type formType = typeof(T);

            Form form;
            if (!_formCache.TryGetValue(formType, out form) || form.IsDisposed)
            {
                form = new T();
                _formCache[formType] = form;
                form.FormClosed += (s, e) =>
                {
                    _formCache.Remove(formType);
                    form = null;
                };
            }

            // 执行初始化逻辑
            initializer?.Invoke((T)form);

            if (!form.Visible)
            {
                if (mdiParent != null) form.MdiParent = mdiParent;
                form.StartPosition = FormStartPosition.CenterScreen;
                form.Show();

            }
            else
            {
                if (form.WindowState == FormWindowState.Minimized)
                {
                    form.WindowState = FormWindowState.Normal;
                }
                form.Activate();
            }

            return (T)form;
        }
    }
}
